<?php
/**
 * 怎么支持多数据源的操作，比方说多个数据库，
 * 通过不同的adapter来区别
 * 
 * 支持ORM，这个abstractTable其实维护了一个实体的数据库table到PfinalPluginORMKit的映射关系
 * <table,entity>，每个entity支持set方法
 * @author huangyusheng
 * @since 2014-3-7
 * @package project_name.package_name
 */
abstract class PfinalModelAbstract {
	// TODO - Insert your code here
	/**
	 * 
	 * @var Pfinal_Plugin_ActiveRecord
	 */
	protected $activeRecord;
	
	protected $adapter;
	
	protected $schema;
	
	protected $databaseName;
	
	protected $tableName;
	
	protected $primaryId;
		
	const DEFINITION_PRIMARY_KEY = 'PRI';
	
	
	protected $isOrmEnable = false;
	
	/**
	 * 初始化activeRecord插件
	 * @throws Pfinal_Exception_Runtime
	 */
	public function __construct(){
		$this->activeRecord = Pfinal::isRegistedPlugin(new Pfinal_Plugin_ActiveRecord());
		if (null===$this->activeRecord) {
			throw new Pfinal_Exception_Runtime("active record plugin is not added");
		}
		try{
			$this->isOrmEnable = Pfinal::getKernelConfig()->getConstant()->getOrmEnable();
			//初始化adapter信息
			$this->adapter = $this->activeRecord->getDataSource($this->databaseName)->getAdapter();
			$this->getMetaData();
			//do some cache
		}catch(Exception $ex){
			
		}
	}
	
	protected function getMetaData(){
		if (empty($this->schema)){
			if (!empty($this->databaseName)){
				$ddl = new Pfinal_Model_DDL();
				$ddl->desc($this->tableName);
				$this->schema = $this->adapter->call($ddl);
			}
		}
		foreach ($this->schema as $definition){
			if ($definition['Key'] === self::DEFINITION_PRIMARY_KEY){
				$this->primaryId = $definition['Field'];
				break;
			}
		}
	}
	
	/**
	 * activerecord相关的方法
	 */
	public function findById($primaryId){
		$selector = new Pfinal_Model_Selector();
		$selector->from($this->tableName);
		//primaryId是数组，批量查询
		if (is_array($primaryId)){
			$selector->where($this->primaryId.'IN(?)', $primaryId);
		}elseif (is_scalar($primaryId)){
			$selector->where($this->primaryId.'=?', $primaryId);
		}
		
		$dataset = $this->adapter->query($selector);
		//这里返回的是原始的dataset数据，根据是否启动orm来判断返回的数据类型
		if ($this->isOrmEnable){
			return $this->activeRecord->buildEntity($this->tableName,$dataset);
		}else{
			return $dataset;
		}
	}
	
	/**
	 * 
	 */
	public function fetchAll(){
		$selector = new Pfinal_Model_Selector();
		$selector->from($this->tableName);
		$dataset = $this->adapter->query($selector);
		if ($this->isOrmEnable){
			return $this->activeRecord->buildEntity($this->tableName,$dataset);
		}else{
			return $dataset;
		}
	}
	
	/**
	 * 创建表结构
	 * @param unknown_type $schema
	 */
	public function create($schema){
		throw new Pfinal_Exception_Runtime("unimplemented exception!");
	}
	
	public function save(){
		
	}
	
	/**
	 * 
	 * @param unknown_type $status
	 */
	public function delete($tag = array()){
		
	}
	
	protected function insert(Pfinal_Model_Adapter_Interface $adapter = null){
		if (null === $adapter){
			$adapter = new Pfinal_Model_Adapter_RMDBS();
		}
		return new Pfinal_Model_Insert($adapter);
	}
	
}

?>